<template>
    <canvas ref="waveCanvas" class="" style="width: 100%;"></canvas>
</template>

<script setup lang="js">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'

const waveCanvas = ref(null)
let ctx = null
let animationId = null
let offset1 = 0
let offset2 = 0

// 设置Canvas尺寸
const resizeCanvas = () => {
    if (!waveCanvas.value) return

    const canvas = waveCanvas.value
    canvas.width = canvas.clientWidth
    canvas.height = canvas.clientHeight
    drawWave()
}

// 绘制波浪线
const drawWave = () => {
    if (!waveCanvas.value) return

    const canvas = waveCanvas.value
    const width = canvas.width
    const height = canvas.height
    const amplitude = 15 // 波浪高度
    const frequency = 0.02 // 波浪密度

    ctx.clearRect(0, 0, width, height)

    // 绘制上层波浪
    ctx.beginPath()
    ctx.moveTo(0, height / 2)

    for (let x = 0; x <= width; x++) {
        const y = height / 2 + amplitude * Math.sin(x * frequency + offset1)
        ctx.lineTo(x, y)
    }

    ctx.lineTo(width, height)
    ctx.lineTo(0, height)
    ctx.closePath()

    const gradient1 = ctx.createLinearGradient(0, 0, 0, height)
    // 修改此处颜色，添加透明度 (80% 不透明度)
    gradient1.addColorStop(0, 'rgba(255, 255, 255, 0.2)')
    gradient1.addColorStop(1, 'rgba(255, 255, 255, 0.2)')
    ctx.fillStyle = gradient1
    ctx.fill()

    // 绘制下层波浪
    ctx.beginPath()
    ctx.moveTo(0, height / 2)

    for (let x = 0; x <= width; x++) {
        const y = height / 1.8 + amplitude * 0.8 * Math.sin(x * frequency * 0.9 + offset2 + Math.PI)
        ctx.lineTo(x, y)
    }

    ctx.lineTo(width, height)
    ctx.lineTo(0, height)
    ctx.closePath()

    const gradient2 = ctx.createLinearGradient(0, 0, 0, height)
    gradient2.addColorStop(0, 'rgba(255, 255, 255, 0.7)')
    gradient2.addColorStop(1, 'rgba(255, 255, 255, 1)')
    ctx.fillStyle = gradient2
    ctx.fill()
}

// 动画循环
const animate = () => {
    offset1 += 0.04
    offset2 += 0.01
    drawWave()
    animationId = requestAnimationFrame(animate)
}

// 窗口大小变化监听
const handleResize = () => {
    // 使用requestAnimationFrame优化性能
    requestAnimationFrame(resizeCanvas)
}

onMounted(() => {
    nextTick(() => {
        if (!waveCanvas.value) return

        ctx = waveCanvas.value.getContext('2d')
        resizeCanvas()
        animate()

        window.addEventListener('resize', handleResize)
    })
})

onUnmounted(() => {
    if (animationId) {
        cancelAnimationFrame(animationId)
    }

    window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
canvas {
    display: block;
}
</style>